package cn.lxg.service.impl;

import cn.lxg.dao.IAdminDao;
import cn.lxg.pojo.TAdmin;
import cn.lxg.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private final IAdminDao adminDao = null;

    @Override
    @Transactional
    public String login(TAdmin admin) {
        // 获得库中对应管理员对象
        TAdmin oldAdmin = this.adminDao.findByAccount(admin.getAccount());
        if (oldAdmin == null || oldAdmin.getId() == 0)
            return "登陆失败，该账号不存在";

        // 校验密码是否正确
        if (!oldAdmin.getPassword().equals(admin.getPassword()))
            return "登陆失败，密码错误";

        // 刷新最后登录时间
        oldAdmin.setEndLoginTime(new Date());
        this.adminDao.updateById(oldAdmin);

        // 账号密码都校验正确
        admin.setId(oldAdmin.getId());
        admin.setName(oldAdmin.getName());
        admin.setEndLoginTime(oldAdmin.getEndLoginTime());
        admin.setCreateTime(oldAdmin.getCreateTime());

        return "OK";
    }

    @Override
    @Transactional
    public TAdmin get(Integer id) {
        return this.adminDao.findById(id);
    }

    @Override
    @Transactional
    public String edit(TAdmin admin) {
        // 检测账号是否重复
        TAdmin oldAdmin = this.adminDao.findByAccount(admin.getAccount());
        if (oldAdmin != null && oldAdmin.getId() != admin.getId())
            return "该账号已经存在，编辑资料失败";

        // 查旧管理员
        oldAdmin = this.adminDao.findById(admin.getId());

        // 更新属性
        oldAdmin.setName(admin.getName());
        oldAdmin.setAccount(admin.getAccount());
        oldAdmin.setPassword(admin.getPassword());

        // 保存编辑
        if (this.adminDao.updateById(oldAdmin))
            return "编辑资料成功";
        else
            return "编辑资料失败";
    }
}
